<?php
namespace app\api\controller;

use think\Controller;
use app\api\model\Postdatadb;
use app\erp\model\Goodsdb;

class Changsha extends Controller
{

    protected $ys_config = [
        'geteway' => 'http://api.utecbj.com/erp/api/',
        'partnerId' => 25,
        'siteId' => 113,
        'appId' => 'utec',
        'appKey' => 'yserp',
        'appSecret' => 'duXtRelcYy2sJeqrLpmNvbQO0O0OO0O0O'
    ];

    protected $username = 'changsha_admin';

    protected $password = '12345678';

    protected $member_id = 111;

    protected $site_url = 'http://changsha.mall.utecbj.com/';

    protected $supplierCode = 'bjyscx';

    protected $appKey = '772558434';

    protected $appSecret = 'b949f6176d398e0ecdd134303ba9779a';

    protected $thirdBaseUrl = 'http://123.56.1.26:8080/';

    protected $token = '';

    protected $regCode = '772558434';

    public $request = array();

    public function _initialize()
    {
        define('MEMBER_ID', $this->member_id);
        define('SITE_ID', $this->ys_config['siteId']);
        define('PARTNER_ID', 25);
        header("Access-Control-Allow-Origin: *");
        // header('Content-Type:application/json; charset=utf-8');
        $request = request();
        $this->request = $request->param();
        
        if (strtolower(request()->action()) != 'gettoken') {
            $this->getToken();
        }
        
        // 捕获请求的数据
        /*
         * $postdatadb = new Postdatadb();
         * $postdatadb->param['post_json'] = $this->request;
         * $postdatadb->param['post_url'] = $request->url();
         * $postdatadb->ajaxSave();
         */
    }

    public function index()
    {
        exit('欢迎使用');
    }

    protected function sendInfo($string_uri, $post)
    {
        // $post['config'] = $this->ys_config;
        $json_data = json_encode($post);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->thirdBaseUrl . $string_uri);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-type: application/json;charset='utf-8'"
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }

    protected function getToken()
    {
        $post_json['supplierCode'] = $this->supplierCode;
        $post_json['appKey'] = $this->appKey;
        $post_json['appSecret'] = $this->appSecret;
        $result = $this->sendInfo('csgp/gpApitoken/getToken', $post_json);
        if ($result['code'] != 0) {
            exit($result['msg']);
        }
        $this->token = $result['token'];
    }
    // 查询分类
    public function getCategory($kindName1 = '', $kindName2 = '', $kindName3 = '')
    {
        $post_json['kindName1'] = $kindName1;
        $post_json['kindName2'] = $kindName2;
        $post_json['kindName3'] = $kindName3;
        $post_json['token'] = $this->token;
        $result = $this->sendInfo('csgp/gpApiGoodsKindNm/getGoodsKindNm', $post_json);
        print_r($result);
    }
    // 查询品牌
    public function getBrand($brandNm = '')
    {
        $post_json['brandNm'] = $brandNm;
        $post_json['token'] = $this->token;
        print_r($post_json);
        $result = $this->sendInfo('csgp/gpApiGpBrand/getBrand', $post_json);
        print_r($result);
    }
    // 商品品目及适用分类查询s
    public function allAttr($kindNm = '')
    {
        $post_json['kindNm'] = $kindNm;
        $post_json['token'] = $this->token;
        $result = $this->sendInfo('csgp/gpApiGoodsAttr/getAllAttr', $post_json);
        print_r($result);
    }
    // 属性查询
    public function getAttr($attrKindName = '', $attyType = '')
    {
        $post_json['attrKindName'] = $attrKindName;
        $post_json['attyType'] = $attyType;
        $post_json['token'] = $this->token;
        print_r(json_encode($post_json));
        $result = $this->sendInfo('csgp/gpApiGoodsAttr/getAttr', $post_json);
        print_r($result);
    }
    // 添加商品
    public function addGoods($goods_sku)
    {
        $goodsdb = new Goodsdb();
        $goodsdb->param['goods_sku'] = $goods_sku;
        $get_goods_info = $goodsdb->ajaxFind();
        if ($get_goods_info['audit_state'] != 1) {
            echo '请等待主站管理员审核后重新提交';
            exit();
        } 
        $post_json['token'] = $this->token;
        $post_json['list']['orgCode'] = $this->regCode;
        $post_json['list']['brandNm'] = $get_goods_info['brand_name'];
        $post_json['list']['goodsKindNm'] = $get_goods_info['category_name'];
        $post_json['list']['goodsAttrKindName'] = $get_goods_info['category_api_option'];
        $post_json['list']['goodsName'] = $get_goods_info['goods_name'];
        $post_json['list']['goodsModel'] = $get_goods_info['goods_model'];
        $temp_sale['saleService'] = '暂无信息';
        $temp_sale['type'] = 2;
        $post_json['list']['goodsSaleServices'][0] = $temp_sale;
        $temp = array();
        foreach ($get_goods_info['goods_pictures'] as $key => $val) {
            array_push($temp, array(
                'detailHtml' => $val['save_path'],
                'type' => 0
            ));
        }
        array_push($temp, array(
            'detailHtml' => htmlspecialchars($get_goods_info['goods_content']),
            'type' => 1
        ));
        $post_json['list']['detailHtmls'] = $temp;
        $post_json['list']['goodsPic'] = $get_goods_info['goods_picture']['save_path'];
        $post_json['list']['goodsWeight'] = $get_goods_info['weight'];
        $post_json['list']['factoryName'] = $get_goods_info['product_firm'] ? $get_goods_info['product_firm'] : '无';
        $post_json['list']['unitId'] = $get_goods_info['goods_unit'];
        $post_json['list']['goodsServeType'] = '0,2';
        $post_json['list']['goodsIsBid'] = 0;
        
        if ($get_goods_info['out_goods_sku'] != null) {
            // 修改
            $result = $this->sendInfo('csgp/gpApiGoods/updateSupplyGoods', $post_json);
            if ($result['code'] != 0) {
                echo ('修改商品信息失败：' . $result['msg'] . '<br />');
            } else {
                echo ('修改商品信息成功<br />');
            }
            $sku_id = $this->getSku($get_goods_info['out_goods_sku']);
            $get_goods_info['sku_id'] = $sku_id;
            echo ('修改sku信息：');
            $this->addSku($get_goods_info,1);
            echo ('<br />修改商品价格：');
            $this->updatePrice($get_goods_info);
            echo ('<br />修改商品属性：');
            $this->editAttr($get_goods_info);
            $sale_state = $get_goods_info['sale_state'] == 1 ? 1 : 0;
            $last_sale_state = $get_goods_info['last_sale_state'] == 1 ? 1 : 0;
            if ($sale_state != $last_sale_state) {
                echo ('<br />商品上下架状态：');
                $this->saleState($get_goods_info);
            } else {
                echo ('<br />上下架状态未改变');
            }
            print_r($get_goods_info['out_goods_sku']);
            exit();
        } else {
            // 新增
            $result = $this->sendInfo('csgp/gpApiGoods/addGoods', $post_json);
            if ($result['code'] != 0) {
                // print_r(json_encode($post_json));
                exit($result['msg']);
            } else {
                $result_arr = $result['msg'][0];
                $goods_id = '';
                foreach ($result_arr as $key => $val) {
                    $goods_id = $val;
                }
                $goodsdb->param['goods_sku'] = $goods_sku;
                $goodsdb->ajaxSaveOne('out_goods_sku', $goods_id);
                echo ('商品保存成功：第三方商品编号：' . $goods_id);
                $get_goods_info['out_goods_sku'] = $goods_id;
                echo '<br />添加商品sku：';
                $this->addSku($get_goods_info,0);
                echo '<br />添加商品服务：';
                $this->addService($get_goods_info);
                echo ('<br />商品上下架状态：');
                $this->saleState($get_goods_info);
            }
        }
    }
    // 修改sku 价格
    protected function updatePrice($goods_info)
    {
        $post_json['token'] = $this->token;
        $post_json['list'][0]['skuId'] = $goods_info['sku_id'];
        $post_json['list'][0]['skuPrice'] = $goods_info['api_price'];
        $result = $this->sendInfo('csgp/gpApiGpGoodsSku/updateGoodsSkuPrice', $post_json);
        if ($result['code'] != 0) {
            print_r(json_encode($post_json));
            print_r($result['msg']);
        } else {
            print_r($result);
            if ($result['success'] == true) {
                print_r('修改价格成功<br />');
            } else {
                print_r('修改价格失败' . $result['msg'] . '<br />');
            }
        }
    }
    // 添加商品sku
    protected function addSku($goods_info,$update = 0)
    {
        $post_json['token'] = $this->token;
        
        $post_json['list']['attrKindName'] = $goods_info['category_api_option'];
        $skuPicUrl = array();
        foreach ($goods_info['goods_pictures'] as $key => $val) {
            array_push($skuPicUrl, array(
                'gpApiSkuPic' => $val['save_path']
            ));
        }
        $post_json['list']['skuPicUrl'] = $skuPicUrl;
        $post_json['list']['skuStockTotal'] = $goods_info['view_stock'];
        $post_json['list']['skuStockLow'] = 1;
        $post_json['list']['goodsId'] = $goods_info['out_goods_sku'];
        if ($update == 0) {
            $post_json['list']['skuPrice'] = $goods_info['api_price'];
            $post_json['list']['skuDefault'] = 1;
        } else {
            $post_json['list']['skuId'] = $goods_info['sku_id'];
        }
        $i = 0;
        $attrParameter = array();
        foreach ($goods_info['goods_attr'] as $key => $val) {
            if ($val['group_name'] == '规格') {
                $i ++;
                if ($i == 1) {
                    $post_json['list']['attrValue1'] = $val['attr_value'];
                } elseif ($i == 2) {
                    $post_json['list']['attrValue2'] = $val['attr_value'];
                } elseif ($i == 3) {
                    $post_json['list']['attrValue3'] = $val['attr_value'];
                }
            } else {
                array_push($attrParameter, array(
                    'attrNm' => $val['attr_name'],
                    'attrValue' => $val['attr_value']
                ));
            }
        }
        $post_json['list']['attrParameter'] = $attrParameter;
        if ($update == 0) {
            $result = $this->sendInfo('csgp/gpApiGpGoodsSku/addGoodsSku', $post_json);
        } else {
            $result = $this->sendInfo('csgp/gpApiGpGoodsSku/updateGoodsSku', $post_json);
        }

        $flag = 0;
        if ($result['code'] != 0) {
            if ($update == 0) {
                echo ($result['msg'][0]['失败信息']);
            } else {
                
            }
        } else {
            if ($result['success'] == true) {
                echo ('添加sku成功<br />');
                $flag = 1;
            } else {
                print_r($result['msg']);
                echo ('添加sku失败<br />');
            }
        }
        if ($flag == 0) {
            echo '<br />设置下架，修改信息后重新提交!';
            $this->saleState($goods_info);
            $goodsdb = new Goodsdb();
            $goodsdb->param['goods_sku'] = $goods_info['goods_sku'];
            $goodsdb->ajaxSaveOne('out_goods_sku', null);
            $goods_info['sale_state'] = 0;
            exit();
        }
    }

    protected function addService($goods_info)
    {
        $post_json['token'] = $this->token;
        $post_json['list']['goodsId'] = $goods_info['out_goods_sku'];
        $post_json['list']['InstallServe'] = $goods_info['is_install'] == 1 ? 1 : 0;
        $post_json['list']['saleServe'] = 0;
        $post_json['list']['qualityTime'] = 4;
        $post_json['list']['installPrice'] = 0;
        $post_json['list']['extendDate'] = 0;
        $post_json['list']['extendPrice'] = 0;
        $result = $this->sendInfo('csgp/gpApiService/addGoodsService', $post_json);
        if ($result['code'] != 0) {
            print_r(json_encode($post_json));
            print_r($result['msg']);
        } else {
            print_r('添加服务成功<br />');
        }
    }
    // 查询商品
    public function getGoods($brand = '')
    {
        $post_json['token'] = $this->token;
        $post_json['orgCode'] = $this->regCode;
        if ($brand) {
            $post_json['brandNm'] = $brand;
        }
        $result = $this->sendInfo('csgp/gpApiGoods/getSupplyGoods', $post_json);
        print_r($result);
    }
    // 查询第三方sku商品
    public function getSku($out_goods_sku)
    {
        $post_json['token'] = $this->token;
        $post_json['list']['goodsId'] = $out_goods_sku;
        $result = $this->sendInfo('csgp/gpApiGpGoodsSku/getGoodsSku', $post_json);
        if ($result['code'] == 0) {
            $skuId = $result['list'][0][0]['skuId'];
            return $skuId;
        } else {
            print_r('没有找到对应的sku');
            exit();
        }
    }
    // 修改sku属性
    public function editAttr($goods_info)
    {
        $get_old_attr = $this->getAttrId($goods_info['out_goods_sku']);
        $list = array();
        foreach ($get_old_attr as $key => $val) {
            foreach ($goods_info['goods_attr'] as $k => $v) {
                if ($val['attrNm'] == $v['attr_name']) {
                    if ($val['attrValue'] != $v['attr_value']) {
                        $temp = array();
                        $temp['uuid'] = $val['uuid'];
                        $temp['upAttrParameter'] = $v['attr_value'];
                        array_push($list, $temp);
                    }
                }
            }
        }
        if (! empty($list)) {
            $post_json['token'] = $this->token;
            $post_json['list'] = $list;
            $result = $this->sendInfo('csgp/gpApiGpGoodsSku/updateGoodsSkuAttrValue', $post_json);
            if ($result['code'] == 0) {
                print_r('属性修改成功');
            } else {
                print_r($result['msg']);
            }
        } else {
            print_r('属性未修改');
        }
    }
    // 查询属性id
    public function getAttrId($out_goods_sku)
    {
        $post_json['token'] = $this->token;
        $post_json['goodsId'] = $out_goods_sku;
        $result = $this->sendInfo('csgp/gpApiGpGoodsSku/getGoodsAttr', $post_json);
        return $result['list'];
    }
    // 商品上下架状态
    public function saleState($goods_info)
    {
        $post_json['token'] = $this->token;
        $list = array();
        $list['goodsId'] = $goods_info['out_goods_sku'];
        if ($goods_info['sale_state'] == 1) {
            // 待备案
            $list['goodsState'] = 1;
        }
        $post_json['list'] = $list;
        $result = $this->sendInfo('csgp/gpApiGpGoodsSku/updateGoodsPublishStatus', $post_json);
        if ($result['code'] == 0) {
            /*
             * $result_msg = '';
             * foreach ($result['msg'] as $key => $val) {
             * foreach ($val as $k => $v) {
             * $result_msg = $v;
             * }
             * }
             * echo $result_msg;
             */
            echo '状态设置成功';
        } else {
            print_r($result['msg']);
        }
    }
}